<template>
  <div class="transfer-admin layout-content">
    <c-table
      :data="data"
      :columns="columns"
      rowKey="userId"
      @onReload="init"
      :loading="loading"
      :scroll="{ y: '90vh' }"
    >
      <template slot="roleName" slot-scope="{ row }">
        <c-tags
          :data="[row.roleName]"
          randomColor
          :colorGroup="['blue']"
        ></c-tags>
      </template>
      <template slot="companyDirection" slot-scope="{ row }">
        <c-button type="link" class="changeBtn" @click="openModal(row)"
          >更换超级管理员</c-button
        >
      </template>
    </c-table>
    <c-modal
      v-model="visible"
      title="账户验证"
      destroyOnClose
      @ok="transfer"
      @cancel="modalCancel"
    >
      <div class="transfer-admin-form">
        <div class="title-verify tc">
          请输入
          <span>{{ user.userData && user.userData.phone }}</span>
          手机号收到的验证码
        </div>
        <c-form
          v-model="form"
          ref="form"
          :data="transferForm"
          :rules="rules"
          :showLabel="false"
          @validate="validate"
        >
          <template v-slot:captchaCode="{ change }">
            <a-input-group compact>
              <a-input
                v-model="form.captchaCode"
                ref="userNameInput"
                style="width: 65%"
                placeholder="请输入图形验证码"
                @change="change('captchaCode')"
              >
                <c-icon type="tupian" slot="prefix" />
              </a-input>
              <img
                :src="graphicUrl"
                style="width: 35%"
                class="cursor-pointer graphicCode"
                @click="getCaptchaCode"
                alt=""
                v-if="graphicUrl"
              />
              <c-button
                type="primary"
                width="35%"
                @click="getCaptchaCode"
                v-else
                >获取验证码</c-button
              >
            </a-input-group>
          </template>
          <template v-slot:phoneCode="{ change }">
            <a-input-group compact>
              <a-input
                v-model="form.phoneCode"
                style="width: 65%"
                @change="change('registerCode')"
                placeholder="请输入验证码"
              >
                <template v-slot:prefix>
                  <c-icon type="xiaoxi" />
                </template>
              </a-input>
              <c-button
                type="primary"
                width="35%"
                :loading="getRegisterCodeLoading"
                :disabled="getRegisterCodeDisabled"
                @click="getMsgCode"
                >{{ getRegisterCodeText }}</c-button
              >
            </a-input-group>
          </template>
        </c-form>
      </div>
    </c-modal>
  </div>
</template>

<script>
import {
  getSpecialUsers,
  transferAdminCaptcha,
  transferAdminCode,
  transferAdmin
} from "@/api/company";
// import dictStaff from "@/dict/staff";
import { mapState, mapActions } from "vuex";

const columns = [
  {
    title: "员工姓名",
    dataIndex: "userName",
    key: "userName"
  },
  {
    title: "手机号码",
    dataIndex: "phone",
    key: "phone"
  },
  {
    title: "员工角色",
    key: "roleName",
    scopedSlots: { customRender: "roleName" }
  },
  {
    // title: "业务方向",
    // key: "companyDirection",
    scopedSlots: { customRender: "companyDirection" },
    width: 1
  }
];
const transferForm = [
  {
    label: "图形验证码",
    prop: "captchaCode",
    slot: "captchaCode"
  },
  {
    label: "短信验证码",
    prop: "phoneCode",
    slot: "phoneCode"
  }
];
export default {
  data() {
    return {
      data: [],
      columns: columns,
      loading: false,
      visible: false,
      transferForm: transferForm,
      form: {
        captchaCode: null,
        phoneCode: null
      },
      rules: {
        captchaCode: [
          { required: true, message: "请输入图形验证码", trigger: "change" }
        ],
        phoneCode: [
          { required: true, message: "请输入验证码", trigger: "change" }
        ]
      },
      graphicUrl: null,
      transferUser: {},
      getRegisterCodeText: "获取验证码",
      getRegisterCodeDisabled: true,
      getRegisterCodeLoading: false,
      bodyStyle: { width: "300px", margin: "auto" }
    };
  },
  computed: {
    ...mapState(["user"])
  },
  methods: {
    ...mapActions(["logout"]),
    // 获取业务方向
    // getDirection(val) {
    //   let res = this.$getEnum(dictStaff.companyDirection, val);
    //   return res;
    // },
    ...mapActions(["silentLogin"]),
    getCaptchaCode() {
      transferAdminCaptcha().then(res => {
        this.graphicUrl = URL.createObjectURL(res);
      });
    },
    getMsgCode() {
      this.getRegisterCodeLoading = true;
      transferAdminCode({
        phone: this.user.userData.phone,
        captchaCode: this.form.captchaCode
      })
        .then(() => {
          this.countdown();
          this.$message.success("短信发送成功");
          this.getRegisterCodeDisabled = true;
        })
        .finally(() => {
          this.getRegisterCodeLoading = false;
        });
    },
    init() {
      this.loading = true;
      getSpecialUsers()
        .then(res => {
          this.data = res;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 提交
    transfer() {
      this.$refs.form.validated().then(() => {
        transferAdmin({
          targetUserId: this.transferUser.userId,
          roleId: this.transferUser.roleId,
          verifyCode: this.form.phoneCode
        }).then(() => {
          // 退登
          this.logout().then(() => {
            this.visible = false;
            this.$router.push({ name: "home" });
            this.$notification.success({
              message: "成功更换超级管理员",
              description: "请重新登录"
            });
          });
        });
      });
    },
    // 触发表单校验的回调事件
    validate(data) {
      if (data.prop === "captchaCode")
        this.getRegisterCodeDisabled = !data.status;
    },
    // 发送短信倒计时
    countdown() {
      let sec = 120;
      let timer = setInterval(() => {
        if (sec <= 0) {
          this.getRegisterCodeText = "获取验证码";
          this.getRegisterCodeDisabled = false;
          clearInterval(timer);
        } else {
          this.getRegisterCodeText = `重发(${sec--}s)`;
        }
      }, 1000);
    },
    modalCancel() {
      // 重置表单
      this.form = {
        captchaCode: null,
        phoneCode: null
      };
      // this.graphicUrl = null;
    },
    openModal(row) {
      this.visible = true;
      this.transferUser = row;
      this.getCaptchaCode();
    }
  },
  created() {
    this.init();
  }
};
</script>

<style lang="scss" scoped>
@import "@/styles/theme/color.scss";

.transfer-admin {
  ::v-deep .ant-table-row td:last-child {
    position: relative;
  }
  .changeBtn {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    right: 10px;
  }
  .title-verify {
    margin-bottom: 20px;
    font-size: 16px;
  }
  .graphicCode {
    // border: 1px solid #d9d9d9;
    // border-left: 0;
    height: 32px;
    padding: 0 5px;
  }
  ::v-deep.ant-input-prefix .iconfont {
    @extend .primary;
  }
  .transfer-admin-form {
    width: 300px;
    margin: auto;
  }
}
</style>
